import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import AMapLoader from '@amap/amap-jsapi-loader';
import {
  DeleteOutlined,
  EditOutlined,
  DownloadOutlined,
  ToTopOutlined,
  PlusOutlined,
  SearchOutlined,
  RightOutlined,
  LeftOutlined,
} from '@ant-design/icons';

import type { LocationTreeEntity } from '@/api/deviceLocationApi';
import {
  deviceLocationDelete,
  deviceLocationExport,
  deviceLocationGetTree,
  deviceLocationSaveOrUpdate,
  deviceLocationImport,
  deviceLocationGetBindDevice,
  deviceLocationUnbind,
  deviceLocationBatchDelete,
} from '@/api/deviceLocationApi';
import { deviceGraphListApi, deviceGroupDetailApi } from '@/api/deviceGraphApi';
import { deviceManagerListApi } from '@/api/deviceManagerApi';
import { deviceGroupListApi } from '@/api/deviceGroupApi';
import { VideoMonitorListApi } from '@/api/videoMonitorApi'; // 添加导入视频监控API
import AmapBox from '@/components/AmapBox';
import SvgIcon from '@/components/SvgIcon';
import RemoteSelect from '@/components/RemoteSelect';
import amapConfig from '@/config/amap';
import { OperationTypeList, type OperationType } from '@/constants';
import { downloadUtils } from '@/utils';

// 导入组态图相关组件
import GraphView from '../Graph/view';

import type { DataNode } from 'antd/es/tree';

import './index.scss';

// 定义FetchParams类型
interface FetchParams {
  page: number;
  pageSize: number;
  searchValue?: string;
  [key: string]: any;
}

/**
 * 高德地图API类型定义
 */
interface AMapAPI {
  Map: new (container: HTMLElement | null, options: Record<string, unknown>) => AMapInstance;
  Marker: new (options: Record<string, unknown>) => AMapMarker;
  ToolBar: new () => unknown;
  Scale: new () => unknown;
}

interface AMapInstance {
  addControl(control: unknown): void;
  add(marker: AMapMarker): void;
  panTo(position: [number, number]): void;
  setZoom(zoom: number): void;
  destroy(): void;
  clearMap?(): void;
}

interface AMapMarker {
  on(event: string, callback: () => void): void;
}

/**
 * 扩展的树节点类型，包含位置数据
 */
export interface LocationTreeNode extends DataNode {
  id: string;
  title: string;
  value: string;
  key: string;
  remark?: string;
  data: LocationTreeEntity;
  children?: LocationTreeNode[];
  isLeaf?: boolean;
}

/**
 * 地址信息类型
 */
interface AddressInfo {
  address: string;
  location: {
    lat: number;
    lng: number;
  };
}

/**
 * 高德地图全局声明
 */
declare global {
  interface Window {
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
  }
}

/** 获取组态图 */
const fetchRemoteSelectDataGraph = async (params: FetchParams) => {
  const res = await deviceGraphListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: v.name || '未命名组态图',
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};

/** 获取设备列表 */
const fetchRemoteSelectDataDevice = async (params: FetchParams) => {
  const res = await deviceManagerListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: `${v.deviceName}-${v.code}`,
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};
/** 获取设备分组列表 */
const fetchRemoteSelectDataDeviceGroup = async (params: FetchParams) => {
  const res = await deviceGroupListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: `${v.groupName}(${v.deviceCount || 0})`,
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};

/** 获取摄像头列表 */
const fetchRemoteSelectDataCamera = async (params: FetchParams) => {
  const res = await VideoMonitorListApi(params);
  if (res.success) {
    const { page, pageSize } = params;
    const hasMore = page * pageSize < res.data.total;

    return {
      data: res.data.records.map(v => {
        return {
          ...v,
          label: `${v.deviceName || v.name || '未命名摄像头'}-${v.code || ''}`,
          value: v.id,
        };
      }),
      total: res.data.total,
      hasMore,
    };
  }
  return {
    data: [],
    total: 0,
    hasMore: false,
  };
};

const tmpUl =
  'http://117.176.131.209:8011/%E4%BD%8D%E7%BD%AE%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx';
/**
 * 设备位置管理组件
 * 提供位置的增删改查功能，支持地图展示和位置选择
 */
const DeviceLocation: React.FC = () => {
  // 路由导航
  const navigate = useNavigate();

  // 高德地图API引用
  const AMapRef = useRef<AMapAPI>({} as AMapAPI);

  // 地图容器引用
  const mapRef = useRef<HTMLDivElement>(null);

  // 地图相关状态
  const [mapOpen, setMapOpen] = useState(false);
  const [map, setMap] = useState<AMapInstance | null>(null);
  const [_mapLoading, _setMapLoading] = useState(false);

  // 组态图相关状态
  const [showGraph, setShowGraph] = useState(false);
  const [currentGraphId, setCurrentGraphId] = useState<string | number | undefined>(undefined);
  const [graphElements, setGraphElements] = useState<any[]>([]);
  const [currentGraphData, setCurrentGraphData] = useState<any>(null);
  const [graphLoading, setGraphLoading] = useState(false);
  const [graphError, setGraphError] = useState<Error | null>(null);

  // 搜索和树形控件状态
  const [searchValue, setSearchValue] = useState('');
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  // 绑定设备列表状态
  const [bindDevices, setBindDevices] = useState<
    Array<{
      id: string;
      deviceName: string;
      productName?: string;
      code?: string;
      online?: boolean | null;
    }>
  >([]);
  const [deviceListLoading, setDeviceListLoading] = useState(false);
  const [isDeviceListCollapsed, setIsDeviceListCollapsed] = useState(false);

  // 表单实例
  const [form] = AForm.useForm();

  // 数据状态
  const [treeData, setTreeData] = useState<LocationTreeEntity[]>([]);
  const [treeArray, setTreeArray] = useState<LocationTreeEntity[]>([]);
  const [_loading, _setLoading] = useState(false);

  // 抽屉状态
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerShowTwo, setDrawerShowTwo] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<LocationTreeEntity>>({});
  const [_submitting, _setSubmitting] = useState(false);

  // 互斥状态标记
  const [hasConfigDiagram, setHasConfigDiagram] = useState(false);
  const [hasBindDevices, setHasBindDevices] = useState(false);

  // 添加一个单独的状态来控制组态图选择器的禁用状态
  const [disableConfigSelection, setDisableConfigSelection] = useState(false);

  // 摄像头类型选项
  const cameraTypeOptions = [
    { label: 'IPcamera', value: 0 },
    { label: 'NVR', value: 1 },
  ];

  const bindType = AForm.useWatch('bindType', form);
  const groupId = AForm.useWatch('groupId', form);
  const cameraCategory = AForm.useWatch('cameraCategory', form); // 添加摄像头分类监听
  const deviceParams = useMemo(() => {
    return {
      groupId: bindType == 1 ? '' : groupId,
    };
  }, [groupId, bindType]);

  // 添加摄像头分类参数
  const cameraParams = useMemo(() => {
    return {
      type: cameraCategory,
    };
  }, [cameraCategory]);

  /**
   * 根据搜索值过滤树数组并按parentId重新组装成树结构
   * @param treeArray 位置树数组（扁平结构）
   * @param searchValue 搜索关键词
   * @returns 重组后的树结构数组
   */
  const searchTree = (
    treeArray: LocationTreeEntity[],
    searchValue: string
  ): LocationTreeEntity[] => {
    if (!treeArray || treeArray.length === 0) {
      return [];
    }

    // 如果没有搜索值，直接按parentId重组
    let filteredArray = treeArray;

    // 如果有搜索值，先过滤出符合条件的节点
    if (searchValue && searchValue.trim() !== '') {
      filteredArray = treeArray.filter(
        item => item.name && item.name.toLowerCase().includes(searchValue.toLowerCase())
      );
    }
    // 创建一个映射表，用于快速查找节点
    const nodeMap: Record<string, LocationTreeEntity> = {};
    filteredArray.forEach(node => {
      nodeMap[node.id] = { ...node, children: [] };
    });

    // 构建树结构
    const result: LocationTreeEntity[] = [];
    filteredArray.forEach(node => {
      const currentNode = nodeMap[node.id];
      if (node.parentId && nodeMap[node.parentId]) {
        // 如果有父节点且父节点在过滤后的数组中，将当前节点添加到父节点的children中
        nodeMap[node.parentId].children!.push(currentNode);
      } else {
        // 如果没有父节点或父节点不在过滤后的数组中，将当前节点添加到结果数组中
        result.push(currentNode);
      }
    });

    return result;
  };

  const newTreeArray = useMemo(() => {
    return searchTree(treeArray, searchValue);
  }, [treeArray, searchValue]);

  /**
   * 将位置树数据转换为Antd Tree组件所需的格式
   * @param treeData 位置树数据
   * @param id 当前编辑的节点ID（用于禁用自身）
   * @returns 转换后的树节点数组
   */
  const treeDataToAntdTree = (treeData: LocationTreeEntity[], id?: string): LocationTreeNode[] => {
    return treeData.map(item => {
      return {
        key: item.id,
        id: item.id,
        value: item.id,
        data: item,
        disabled: item.id == id,
        title: item.name || '未命名',
        children: item.children ? treeDataToAntdTree(item.children, id) : undefined,
      };
    });
  };

  /**
   * 将树形结构转换为扁平数组
   * @param treeData 树形数据
   * @returns 扁平化的数组
   */
  const treeToArray = (treeData: LocationTreeEntity[]): LocationTreeEntity[] => {
    return treeData.flatMap(node => {
      const { children, ...rest } = node;
      return [rest, ...(children ? treeToArray(children) : [])];
    });
  };

  /**
   * 获取位置树列表数据
   */
  const getTreeList = async () => {
    try {
      _setLoading(true);

      const res = await deviceLocationGetTree({ searchValue });

      if (res.success && res.data) {
        setTreeData(res.data);
        const newData = treeToArray(res.data);
        setTreeArray(newData);
        const keys = newData.filter(v => v.parentId < 1).map(v => v.id);
        setExpandedKeys(keys);
      } else {
        window.$message.error(res.message || '获取位置数据失败');
      }
    } catch (error) {
      console.error('获取位置树失败:', error);
      window.$message.error('获取位置数据失败，请稍后重试');
    } finally {
      _setLoading(false);
    }
  };

  /**
   * 在地图上设置位置标记
   */
  const setMarker = () => {
    if (map && treeArray.length > 0) {
      // 清除现有标记
      map.clearMap?.();

      treeArray.forEach(markerData => {
        // 检查位置数据是否有效
        if (!markerData.lng || !markerData.lat) {
          return;
        }

        const marker = new AMapRef.current.Marker({
          position: [markerData.lng, markerData.lat],
          title: markerData.name,
          content: `<div class="custom-marker">${markerData.name}<br/></div>`,
        });

        // 添加点击事件
        marker.on('click', () => {
          window.$message.info(`点击了 ${markerData.name}，位置：${markerData.address || '未知'}`);
        });

        map.add(marker);
      });
    } else if (map) {
      // 如果地图已加载但数据还未准备好，延迟重试
      setTimeout(() => {
        setMarker();
      }, 1000);
    }
  };

  useEffect(() => {
    setMarker();
  }, [map, treeArray]);

  useEffect(() => {
    getTreeList();
  }, []);

  /**
   * 初始化高德地图
   */
  useEffect(() => {
    if (!mapRef.current) return;

    // 设置高德地图安全密钥
    if (!window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: amapConfig.amapCode,
      };
    }

    const initMap = async () => {
      try {
        _setMapLoading(true);

        const AMap = await AMapLoader.load({
          key: amapConfig.amapKey,
          version: '2.0',
          plugins: [
            'AMap.Scale',
            'AMap.ToolBar',
            'AMap.Marker',
            'AMap.MoveAnimation',
            'AMap.MouseTool',
            'AMap.Geocoder',
            'AMap.AutoComplete',
          ],
        });

        AMapRef.current = AMap;

        const mapInstance = new AMap.Map(mapRef.current, {
          zoom: 14,
          center: [104.6417, 28.7513], // 默认中心点（成都）
          pitch: 0,
          mapStyle: 'amap://styles/normal', // 标准地图样式
        });

        // 添加地图控件
        mapInstance.addControl(new AMap.ToolBar());
        mapInstance.addControl(new AMap.Scale());

        setMap(mapInstance);
      } catch (error) {
        console.error('地图加载失败:', error);
        window.$message.error('地图加载失败，请检查网络连接或API密钥配置');
      } finally {
        _setMapLoading(false);
      }
    };

    initMap();

    // 清理函数
    return () => {
      if (map) {
        map.destroy();
        setMap(null);
      }
    };
  }, [mapRef.current]);

  /**
   * 处理新增位置按钮点击
   */
  const handleAddLocation = () => {
    setDrawerType('ADD');
    setDrawerShow(true);
    setCurrentRecord({});
    form.resetFields();
    // 新增模式下重置互斥状态
    setHasConfigDiagram(false);
    setHasBindDevices(false);
  };

  /**
   * 处理导出位置信息
   */
  const handleExportLocation = async () => {
    try {
      const response = await deviceLocationExport();
      const res = response as Response;

      if (res.status === 200) {
        downloadUtils.downloadFromResponse(res, '位置信息.xlsx');
        window.$message.success('位置信息导出成功');
      } else {
        const resData = downloadUtils.deCodeArrayBuffer(res.blob());
        if (resData && resData.errorCode) {
          window.$message.error(resData.errorMsg || '导出失败');
        } else {
          window.$message.error('导出失败，请稍后重试');
        }
      }
    } catch (error) {
      console.error('导出位置信息失败:', error);
      window.$message.error('导出失败，请稍后重试');
    }
  };

  // 修改后的搜索处理
  const handleSearch = (value: string) => {
    setSearchValue(value);
  };

  /**
   * 获取位置绑定的设备列表
   * @param locationId 位置ID
   */
  const getBindDevices = async (locationId: string) => {
    if (!locationId) return;

    try {
      setDeviceListLoading(true);
      const res = await deviceLocationGetBindDevice({ locationId });

      if (res.success && Array.isArray(res.data)) {
        // 确保数据是数组并且满足类型要求
        setBindDevices(
          res.data.map((item: any) => ({
            id: item.id || '',
            deviceName: item.deviceName || '',
            productName: item.productName || undefined,
            productCode: item.productCode,
            code: item.code || undefined,
            online: item.online !== undefined ? item.online : null,
          }))
        );
      } else {
        setBindDevices([]);
        window.$message.error(res.message || '获取绑定设备失败');
      }
    } catch (error) {
      console.error('获取绑定设备失败:', error);
      window.$message.error('获取绑定设备列表失败');
      setBindDevices([]);
    } finally {
      setDeviceListLoading(false);
    }
  };

  /**
   * 解绑设备
   * @param deviceId 设备ID
   */
  const handleUnbindDevice = async (deviceId: string) => {
    try {
      const res = await deviceLocationUnbind(deviceId);

      if (res.success) {
        window.$message.success('设备解绑成功');
        // 刷新绑定设备列表
        if (selectedKeys.length > 0) {
          await getBindDevices(selectedKeys[0] as string);
        }
      } else {
        window.$message.error(res.message || '设备解绑失败');
      }
    } catch (error) {
      console.error('设备解绑失败:', error);
      window.$message.error('设备解绑失败，请稍后重试');
    }
  };

  /**
   * 处理树节点选择
   * @param selectedKeys 选中的节点key数组
   */
  const handleTreeSelect = async (selectedKeys: React.Key[]) => {
    setSelectedKeys(selectedKeys);

    if (selectedKeys.length > 0) {
      const selectedKey = selectedKeys[0] as string;
      const activeItem = treeArray.find(v => v.id === selectedKey);

      // 地图定位到选中的位置（无论是否有组态图都定位）
      if (map && activeItem?.lng && activeItem?.lat) {
        map.panTo([activeItem.lng, activeItem.lat]);
        map.setZoom(16); // 放大到更详细的级别
      }

      // 获取绑定的设备列表
      await getBindDevices(selectedKey);

      // 检查是否绑定了组态图
      if (activeItem?.configDiagramId) {
        // 显示组态图浮动层
        setShowGraph(true);
        setCurrentGraphId(activeItem.configDiagramId);
      } else {
        // 隐藏组态图浮动层
        setShowGraph(false);
        setCurrentGraphId(undefined);
      }
    } else {
      // 没有选中任何节点，隐藏组态图浮动层
      setShowGraph(false);
      setGraphElements([]);
      setCurrentGraphData(null);
      setGraphLoading(false);
      setGraphError(null);
      setBindDevices([]);
    }
  };

  /**
   * 关闭抽屉并重置表单
   */
  const handleDrawerClose = () => {
    form.resetFields();
    setDrawerShow(false);
    setDrawerShowTwo(false);
    setCurrentRecord({});

    // 重置互斥状态
    setHasConfigDiagram(false);
    setHasBindDevices(false);
    setDisableConfigSelection(false); // 添加重置禁用状态
  };

  /**
   * 关闭抽屉并重置表单
   */
  const handleDrawerCloseTwo = () => {
    setDrawerShowTwo(false);
  };

  /**
   * 处理表单提交（新增/编辑）
   */
  const handleSubmit = async () => {
    try {
      _setSubmitting(true);

      const params = await form.validateFields();
      console.log('表单参数:', params);

      // 检查互斥条件
      const deviceIds = params.deviceIds || [];
      const cameraIds = params.cameraIds || [];
      const configDiagramId = params.configDiagramId;

      // 如果同时存在组态图和设备，清除组态图
      if ((deviceIds.length > 0 || cameraIds.length > 0) && configDiagramId) {
        params.configDiagramId = null;
        params.configDiagramName = null;
        window.$message.warning('检测到同时存在组态图和设备绑定，已自动清除组态图');
      }

      const requestData = {
        ...currentRecord,
        ...params,
        // 确保保存摄像头相关的字段
        bindType: params.bindType,
        cameraCategory: params.cameraCategory,
      };

      console.log('提交请求数据:', requestData);

      const response = await deviceLocationSaveOrUpdate(requestData);

      if (response.success) {
        const successMessage = drawerType === 'ADD' ? '位置创建成功' : '位置更新成功';
        window.$message.success(successMessage);
        handleDrawerClose();
        await getTreeList(); // 重新获取数据

        // 如果当前有选中节点，刷新该节点绑定的设备列表
        if (selectedKeys.length > 0) {
          const selectedKey = selectedKeys[0] as string;
          // 获取最新的节点数据
          const updatedItem = treeArray.find(v => v.id === selectedKey);

          // 刷新设备绑定列表
          await getBindDevices(selectedKey);

          // 如果选中节点包含组态图，刷新组态图
          if (updatedItem?.configDiagramId) {
            setShowGraph(true);
            setCurrentGraphId(updatedItem.configDiagramId);
          } else {
            setShowGraph(false);
            setCurrentGraphId(undefined);
          }
        }
      } else {
        window.$message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      // if (error instanceof Error) {
      //   window.$message.error(`操作失败：${error.message}`);
      // } else {
      //   window.$message.error('表单验证失败，请检查输入');
      // }
    } finally {
      _setSubmitting(false);
    }
  };

  /**
   * 处理删除位置
   * @param id 要删除的位置ID
   */
  const handleDelete = async (id: string) => {
    // 参数验证
    if (!id) {
      window.$message.error('删除失败：位置ID不存在');
      return;
    }

    try {
      const response = await deviceLocationDelete({ id });
      if (response.success) {
        window.$message.success('位置删除成功');

        // 如果删除的是当前选中的节点，清空选中状态
        if (selectedKeys.includes(id)) {
          setSelectedKeys([]);
        }

        await getTreeList(); // 重新获取数据
      } else {
        window.$message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      window.$message.error('删除操作失败，请稍后重试');
    }
  };

  /**
   * 处理树节点展开/收起
   * @param expandedKeys 展开的节点key数组
   */
  const handleTreeExpand = (expandedKeys: React.Key[]) => {
    setExpandedKeys(expandedKeys);
  };

  /**
   * 处理树节点拖拽完成事件
   * @param info 拖拽信息
   */
  const handleDrop = async (info: any) => {
    const { dragNode, node, dropToGap, dropPosition } = info;

    try {
      // 获取拖拽节点和目标节点的数据
      const dragNodeId = dragNode.key;
      const targetNodeId = node.key;

      // 查找拖拽节点的原始数据
      const dragNodeData = treeArray.find(item => item.id === dragNodeId);
      if (!dragNodeData) {
        window.$message.error('未找到拖拽节点数据');
        return;
      }

      // 构造更新数据
      const updatedNode = {
        ...dragNodeData,
      };

      // 判断是否更改了父节点
      if (!dropToGap) {
        // 如果是放到节点内容上，则目标节点成为新的父节点
        updatedNode.parentId = parseInt(targetNodeId, 10);
      } else if (
        node.data?.parentId !== undefined &&
        dragNodeData.parentId !== node.data.parentId
      ) {
        // 如果是放到节点间隙，且与原父节点不同，则更改父节点
        updatedNode.parentId = node.data.parentId;
      }

      // 计算新的排序值
      const dropPos = node.pos.split('-');
      const dropTargetIndex = Number(dropPos[dropPos.length - 1]);
      const isAfter = dropPosition > dropTargetIndex;
      const oldSort = Number(node?.data?.sort) || 0;
      if (dropToGap) {
        // 拖拽到间隙中
        if (isAfter) {
          // 落在目标节点之后
          updatedNode.sort = oldSort + 1;
        } else {
          // 落在目标节点之前
          updatedNode.sort = oldSort;
        }
      } else {
        // 拖拽到节点上，成为其子节点
        updatedNode.sort = 0; // 假定新子节点的 sort 值为 0
      }

      // 调用API更新节点
      const response = await deviceLocationSaveOrUpdate(updatedNode);

      if (response.success) {
        window.$message.success('位置排序更新成功');
        await getTreeList(); // 重新获取数据
      } else {
        window.$message.error(response.message || '排序更新失败');
      }
    } catch (error) {
      console.error('排序更新失败:', error);
      window.$message.error('排序更新失败，请稍后重试');
    }
  };

  /**
   * 取消地图选择
   */
  const mapCancel = () => {
    setMapOpen(false);
  };
  /**
   * 地图选择确认回调
   * @param values 地图选择的结果
   */
  const mapOk = (values: unknown) => {
    // 类型断言，确保是地址信息
    const addressInfo = values as AddressInfo;
    form.setFieldsValue({
      lng: addressInfo.location.lng,
      lat: addressInfo.location.lat,
      address: addressInfo.address,
    });
    setMapOpen(false);
  };

  /**
   * 处理新增子节点
   * @param nodeData 父节点数据
   */
  const handleAdd = (nodeData: LocationTreeNode) => {
    setDrawerType('ADD');
    setDrawerShow(true);
    setCurrentRecord({});
    form.setFieldValue('parentId', nodeData?.id);
  };

  /**
   * 处理编辑节点
   * @param nodeData 要编辑的节点数据
   */
  const handleEdit = async (nodeData: LocationTreeNode) => {
    console.log('handleEdit', nodeData);
    setDrawerType('EDIT');
    // 创建一个临时的数据副本，避免直接修改nodeData.data
    const nodeDataCopy = { ...nodeData.data };
    if (nodeDataCopy.configDiagramId) {
      // 只在表单中设置字符串类型，不修改原始数据
      form.setFieldValue('configDiagramId', String(nodeDataCopy.configDiagramId));
    }

    // 设置摄像头相关的表单值
    if (nodeDataCopy.bindType !== undefined) {
      form.setFieldValue('bindType', nodeDataCopy.bindType);
    } else {
      form.setFieldValue('bindType', null); // 确保默认值
    }
    if (nodeDataCopy.cameraCategory !== undefined) {
      form.setFieldValue('cameraCategory', nodeDataCopy.cameraCategory);
    } else {
      form.setFieldValue('cameraCategory', null); // 确保默认值
    }

    // 分别设置摄像头设备ID和普通设备ID
    if (nodeDataCopy.cameraIds !== undefined) {
      form.setFieldValue('cameraIds', nodeDataCopy.cameraIds);
    } else {
      form.setFieldValue('cameraIds', []); // 确保默认值
    }
    if (nodeDataCopy.deviceIds !== undefined) {
      form.setFieldValue('deviceIds', nodeDataCopy.deviceIds);
    } else {
      form.setFieldValue('deviceIds', []); // 确保默认值
    }

    setCurrentRecord(nodeDataCopy);
    form.setFieldsValue(nodeDataCopy);

    // 设置组态图绑定状态
    const hasConfigDiagramValue = !!nodeDataCopy.configDiagramId;
    setHasConfigDiagram(hasConfigDiagramValue);
    console.log('组态图ID:', nodeDataCopy.configDiagramId, '是否有组态图:', hasConfigDiagramValue);

    // 如果有组态图ID但没有组态图名称，尝试获取组态图信息
    if (hasConfigDiagramValue && !nodeDataCopy.configDiagramName) {
      try {
        // 获取组态图详情
        // 组态图ID类型判断
        const configDiagramId = Number(nodeDataCopy.configDiagramId);
        const graphRes = await deviceGroupDetailApi({ id: configDiagramId });
        if (graphRes.success && graphRes.data && graphRes.data.name) {
          form.setFieldValue('configDiagramName', graphRes.data.name);
          console.log('成功获取组态图名称:', graphRes.data.name);
        }
      } catch (error) {
        console.error('获取组态图名称失败:', error);
      }
    }

    // 检查是否已经获取了绑定设备列表，如果已经获取则使用现有数据
    // 判断条件：当前选中节点与要编辑的节点一致，并且已有设备列表数据
    if (selectedKeys.length > 0 && selectedKeys[0] === nodeData.id && bindDevices.length >= 0) {
      console.log('使用已获取的设备列表数据:', bindDevices);
      const hasDevices = bindDevices.length > 0;
      setHasBindDevices(hasDevices);
      if (hasDevices) {
        if (!hasConfigDiagramValue) {
          setDisableConfigSelection(true);
          console.log('设置有绑定设备无组态图: 组态图选择器已禁用');
        } else {
          setDisableConfigSelection(false);
          console.log('同时有组态图和设备: 组态图选择器可用');
        }

        // 根据 bindType 决定将设备 ID 分配给 deviceIds 还是 cameraIds
        const deviceIds = bindDevices.map(item => item.id);
        if (nodeDataCopy.bindType === 3) {
          // 摄像头分类绑定
          form.setFieldValue('cameraIds', deviceIds);
          form.setFieldValue('deviceIds', []); // 清空普通设备ID
        } else {
          // 普通设备绑定
          form.setFieldValue('deviceIds', deviceIds);
          form.setFieldValue('cameraIds', []); // 清空摄像头ID
        }
      } else {
        // 没有绑定设备
        setHasBindDevices(false);
        setDisableConfigSelection(false);
        console.log('设置有绑定设备: false, 没有设备或数组为空, 组态图选择器可用');
        form.setFieldValue('deviceIds', []);
        form.setFieldValue('cameraIds', []);
      }
    } else {
      // 如果没有已获取的数据，才发起新请求
      try {
        const res = await deviceLocationGetBindDevice({ locationId: nodeData.id });
        console.log('绑定设备响应:', res);

        if (res.success && Array.isArray(res.data) && res.data.length > 0) {
          setHasBindDevices(true);
          if (!hasConfigDiagramValue) {
            setDisableConfigSelection(true);
            console.log('设置有绑定设备无组态图: 组态图选择器已禁用');
          } else {
            setDisableConfigSelection(false);
            console.log('同时有组态图和设备: 组态图选择器可用');
          }

          // 根据 bindType 决定将设备 ID 分配给 deviceIds 还是 cameraIds
          const deviceIds = res.data.map((item: any) => item.id);
          if (nodeDataCopy.bindType === 3) {
            // 摄像头分类绑定
            form.setFieldValue('cameraIds', deviceIds);
            form.setFieldValue('deviceIds', []); // 清空普通设备ID
          } else {
            // 普通设备绑定
            form.setFieldValue('deviceIds', deviceIds);
            form.setFieldValue('cameraIds', []); // 清空摄像头ID
          }
        } else {
          // 没有绑定设备
          setHasBindDevices(false);
          setDisableConfigSelection(false);
          console.log('设置有绑定设备: false, 没有设备或数组为空, 组态图选择器可用');
          form.setFieldValue('deviceIds', []);
          form.setFieldValue('cameraIds', []);
        }
      } catch (error) {
        console.error('获取绑定设备失败:', error);
        setHasBindDevices(false);
        setDisableConfigSelection(false);
        console.log('获取设备失败，设置组态图选择器可用');
        form.setFieldValue('deviceIds', []);
        form.setFieldValue('cameraIds', []);
      }
    }

    setDrawerShow(true);
  };

  /**
   * 运行位置信息导入
   */
  const handleImportLocation = async () => {
    try {
      // 创建一个隐藏的 input 元素
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.xlsx,.xls'; // 只接受 Excel 文件
      input.multiple = false; // 只接受单个文件
      input.style.display = 'none';

      // 监听文件选择事件
      input.onchange = async event => {
        const target = event.target as HTMLInputElement;
        const file = target.files?.[0];

        if (!file) {
          return;
        }

        // 验证文件类型
        const allowedTypes = [
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ];

        if (!allowedTypes.includes(file.type)) {
          window.$message.error('只支持 Excel 文件格式(.xls, .xlsx)');
          return;
        }

        // 验证文件大小（限制10MB）
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
          window.$message.error('文件大小不能超过10MB');
          return;
        }

        try {
          // 创建 FormData 并添加文件
          const formData = new FormData();
          formData.append('file', file);
          console.log('currentRecord', selectedKeys);
          // 调用导入 API
          const parentId = selectedKeys.length > 0 ? Number(selectedKeys[0]) || 0 : 0;
          const res = await deviceLocationImport(formData, parentId);

          if (res.success) {
            window.$message.success('位置信息导入成功');
            // 刷新位置树数据
            await getTreeList();
          } else {
            window.$message.error(res.message || '导入失败，请稍后重试');
          }
        } catch (error) {
          console.error('导入位置信息失败:', error);
          window.$message.error('导入失败，请稍后重试');
        } finally {
          // 清理临时创建的 input 元素
          if (input.parentNode) {
            input.parentNode.removeChild(input);
          }
        }
      };

      // 将 input 添加到 DOM 中并触发点击
      document.body.appendChild(input);
      input.click();
    } catch (error) {
      console.error('创建文件选择器失败:', error);
      window.$message.error('操作失败，请稍后重试');
    }
  };

  // 添加批量选中状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /**
   * 处理批量删除位置
   */
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      window.$message.warning('请至少选择一个位置进行删除');
      return;
    }

    try {
      const response = await deviceLocationBatchDelete({ ids: selectedRowKeys as string[] });
      if (response.success) {
        window.$message.success(`成功删除${selectedRowKeys.length}个位置`);
        setSelectedRowKeys([]); // 清空选中项
        await getTreeList(); // 重新获取数据

        // 如果删除的节点中包含当前选中的节点，清空选中状态
        const newSelectedKeys = selectedKeys.filter(key => !selectedRowKeys.includes(key));
        if (newSelectedKeys.length !== selectedKeys.length) {
          setSelectedKeys(newSelectedKeys);
        }
      } else {
        window.$message.error(response.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      window.$message.error('批量删除操作失败，请稍后重试');
    }
  };
  const showTooltips = false;

  return (
    <div className="page-wrapper">
      <AmapBox mapType="addressType" open={mapOpen} onCancel={mapCancel} onOk={mapOk} detail={{}} />
      <div className="page-title">
        <div className="page-main-title">位置管理</div>
        <div className="page-sub-title">使用平面建模技术对物联网设备位置进行精确管理</div>
      </div>
      <div className="page-content-box">
        <div className="page-content flex show-bg location-content">
          <div className="location-sidebar pt-2.5 h-full w-80 md:w-80 w-full  bg-white border-r border-gray-200 flex flex-col relative">
            {/* 右上角浮动的导入模板链接 */}
            <div className="absolute top-[-10px]  left-[-10px] z-10">
              <a
                href={tmpUl}
                className="text-blue-600 hover:text-blue-800 text-xs flex items-center gap-1 bg-blue-50 hover:bg-blue-100 px-2 py-1 rounded-md transition-colors"
                download="位置导入模板.xlsx"
                title="下载导入模板"
              >
                <DownloadOutlined className="text-xs" />
                模板
              </a>
            </div>

            {/* 操作按钮 */}
            <div className="py-2 px-4 border-b border-gray-100 flex gap-2">
              <AButton
                color="primary"
                icon={<ToTopOutlined />}
                onClick={handleImportLocation}
                className="flex-1"
              >
                导入位置信息
              </AButton>
              <AButton
                icon={<DownloadOutlined />}
                color="primary"
                variant="outlined"
                onClick={handleExportLocation}
                className="flex-1"
              >
                导出位置信息
              </AButton>
            </div>
            <div className="py-1 px-4 border-b border-gray-100 flex gap-3">
              <AButton
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddLocation}
                className=" flex-1"
              >
                新增位置
              </AButton>
              {/* 批量删除按钮 */}
              <AButton
                danger
                icon={<DeleteOutlined />}
                onClick={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
                className="flex-1"
              >
                批量删除({selectedRowKeys.length})
              </AButton>
            </div>

            {/* 搜索框 */}
            <div className="p-4 border-b border-gray-100">
              <AInput
                placeholder="请输入位置信息搜索"
                prefix={<SearchOutlined />}
                value={searchValue}
                onChange={e => handleSearch(e.target.value)}
                className="w-full"
              />
            </div>

            {/* 位置树 */}
            <div className="flex-1  flex flex-col overflow-auto p-4">
              <ATree
                className="draggable-tree"
                expandedKeys={expandedKeys}
                blockNode
                selectable
                draggable // 启用拖拽功能
                onExpand={handleTreeExpand}
                treeData={treeDataToAntdTree(newTreeArray, currentRecord?.id || '')}
                selectedKeys={selectedKeys}
                // 添加复选框支持批量选择
                checkable
                checkedKeys={selectedRowKeys}
                onCheck={checkedKeys => {
                  // 允许选择所有节点进行删除
                  const checkedArray = Array.isArray(checkedKeys)
                    ? checkedKeys
                    : checkedKeys.checked;
                  setSelectedRowKeys(checkedArray);
                }}
                // 处理拖拽完成事件
                onDrop={handleDrop}
                // defaultExpandAll
                titleRender={(nodeData: DataNode) => {
                  // 类型断言为LocationTreeNode以访问扩展属性
                  const locationNode = nodeData as LocationTreeNode;
                  // const activeItem = getEnumItem(DeviceLocationType, locationNode.data?.type || 0);
                  return (
                    <div
                      className="flex justify-between items-center w-full tree-node whitespace-nowrap"
                      onClick={e => {
                        handleTreeSelect([nodeData.key]);
                        setSelectedKeys([nodeData.key]);
                        setExpandedKeys(expandedKeys.concat(nodeData.key));
                        e.stopPropagation();
                      }}
                    >
                      {showTooltips && (
                        <ATooltip title={nodeData.title as string}>
                          <ASpace>
                            <span>{nodeData.title as string}</span>
                            {/* 显示组态图绑定状态 */}
                            {locationNode.data?.configDiagramId && (
                              <ATag className="ml-1 text-xs px-1" color="blue">
                                <SvgIcon name="icon-menu-zt" className="text-xs mr-1" />
                                组态图
                              </ATag>
                            )}
                            {/* {activeItem?.label && (
                            <ATag className="ml-1 text-3 px-1" color={activeItem?.color}>
                              {activeItem?.label}
                            </ATag>
                          )} */}
                          </ASpace>
                        </ATooltip>
                      )}
                      <ASpace>
                        <span>{nodeData.title as string}</span>
                        {/* 显示组态图绑定状态 */}
                        {locationNode.data?.configDiagramId && (
                          <ATag className="ml-1 text-xs px-1" color="blue">
                            <SvgIcon name="icon-menu-zt" className="text-xs mr-1" />
                            组态图
                          </ATag>
                        )}
                        {/* {activeItem?.label && (
                            <ATag className="ml-1 text-3 px-1" color={activeItem?.color}>
                              {activeItem?.label}
                            </ATag>
                          )} */}
                      </ASpace>
                      {selectedKeys.includes(nodeData.key) && (
                        <span className="tree-node-operations pl-1">
                          <ASpace onClick={e => e.stopPropagation()}>
                            <PlusOutlined
                              className="text-[13px] color-primary"
                              onClick={() => handleAdd(locationNode)}
                            />
                            <EditOutlined
                              className="text-[13px] color-primary"
                              onClick={() => handleEdit(locationNode)}
                            />
                            <APopconfirm
                              title="您确定要删除吗？"
                              description={`您当前要删除是 ${nodeData.title}`}
                              onConfirm={() => {
                                handleDelete(locationNode.id);
                              }}
                              okType="danger"
                              okText="确认"
                              cancelText="取消"
                            >
                              <DeleteOutlined className="text-[13px] color-error" />
                            </APopconfirm>
                          </ASpace>
                        </span>
                      )}
                    </div>
                  );
                }}
              />
            </div>
          </div>

          {/* 右侧内容区域 - 分为地图/组态图区域和设备列表区域 */}
          <div className="flex-1 relative">
            {/* 地图容器 - 始终显示作为底层 */}
            <div className="w-full h-full bg-gray-100 amap-container z-0">
              <div ref={mapRef} className="w-full h-full" />
            </div>

            {/* 组态图浮动层 - 当有组态图时显示 */}
            {showGraph && (
              <div className="absolute inset-0 bg-white flex flex-col z-10 graph-floating-layer">
                {/* 组态图标题栏 */}
                <div className="graph-header px-4 py-2 flex justify-between items-center">
                  <div className="flex items-center space-x-2">
                    <SvgIcon name="icon-menu-zt" className="text-blue-500" />
                    <span className="text-sm text-gray-500">组态图:</span>
                    <span className="font-medium">
                      {treeArray.find(v => v.id === selectedKeys[0])?.configDiagramName ||
                        '未命名组态图'}
                    </span>
                    {selectedKeys.length > 0 && (
                      <span className="text-xs text-gray-400">
                        (位置: {treeArray.find(v => v.id === selectedKeys[0])?.name})
                      </span>
                    )}
                  </div>
                  <div className="flex items-center space-x-2">
                    <AButton
                      type="primary"
                      size="small"
                      onClick={() => {
                        if (currentGraphId) {
                          // 在当前页面跳转到组态图编辑页面
                          navigate(`/device/graph/edit/${currentGraphId}`);
                        }
                      }}
                      disabled={!currentGraphId}
                    >
                      编辑组态图
                    </AButton>
                    <ADivider type="vertical" />
                    <AButton
                      type="text"
                      size="small"
                      onClick={() => setShowGraph(false)}
                      title="关闭组态图"
                      className="close-button"
                    >
                      ✕
                    </AButton>
                  </div>
                </div>

                {/* 组态图画布 */}
                <div className="flex-1 overflow-hidden">
                  <GraphView id={currentGraphId as string} />
                </div>
              </div>
            )}

            {/* 地图提示信息 - 当没有选中节点或没有组态图时显示 */}
            {!showGraph && selectedKeys.length === 0 && (
              <div className="absolute top-4 left-4 bg-white bg-opacity-90 px-3 py-2 rounded-md shadow-sm z-20">
                <div className="text-sm text-gray-600">
                  <SvgIcon name="icon-location" className="mr-1" />
                  请选择左侧位置节点查看详情
                </div>
              </div>
            )}

            {/* 设备绑定列表浮动层 - 从右向左浮动 */}
            {selectedKeys.length > 0 && (
              <div
                className={`absolute right-0 top-0 bottom-0 bg-white border-l border-gray-200 shadow-lg flex flex-col z-[100] transition-all duration-300 ease-in-out device-bind-list ${
                  isDeviceListCollapsed ? 'w-12' : 'w-80'
                }`}
              >
                {isDeviceListCollapsed ? (
                  <div
                    className="flex-1 flex items-center justify-center cursor-pointer relative"
                    onClick={() => setIsDeviceListCollapsed(false)}
                  >
                    <AButton
                      type="text"
                      size="small"
                      icon={<LeftOutlined />}
                      onClick={e => {
                        e.stopPropagation();
                        setIsDeviceListCollapsed(false);
                      }}
                      className="!absolute top-4 right-0.5"
                    />
                    <div
                      style={{ writingMode: 'vertical-rl' }}
                      className="text-base text-gray-600 tracking-wider"
                    >
                      设备绑定列表
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="p-4 border-b border-gray-100 font-medium flex justify-between items-center bind-list-header">
                      <div className="flex items-center">
                        <SvgIcon name="icon-bind" className="mr-2 text-blue-500" />
                        <span className="text-base">设备绑定列表</span>
                      </div>
                      <div className="flex items-center">
                        <div
                          className="text-xs text-gray-500 truncate max-w-[120px] mr-2"
                          title={treeArray.find(v => v.id === selectedKeys[0])?.name}
                        >
                          {treeArray.find(v => v.id === selectedKeys[0])?.name}
                        </div>
                        <AButton
                          type="text"
                          size="small"
                          icon={<RightOutlined />}
                          onClick={() => setIsDeviceListCollapsed(true)}
                        />
                      </div>
                    </div>

                    <div className="flex-1 overflow-auto p-2">
                      {deviceListLoading ? (
                        <div className="p-6 flex justify-center">
                          <ASpin tip="加载中..." />
                        </div>
                      ) : bindDevices.length > 0 ? (
                        <div className="device-list">
                          {bindDevices.map(item => (
                            <div key={item.id} className="device-item">
                              <div className="flex justify-between items-start mb-2">
                                <div className="flex items-center">
                                  <span className="device-name" title={item.id}>
                                    {item.id}
                                  </span>
                                  <span className="device-name" title={item.deviceName}>
                                    {item.deviceName}
                                  </span>
                                  {item.online !== undefined && item.online !== null ? (
                                    <ATag
                                      color={item.online ? 'success' : 'error'}
                                      className="ml-2"
                                    >
                                      {item.online ? '在线' : '离线'}
                                    </ATag>
                                  ) : null}
                                </div>
                                <APopconfirm
                                  title="确认解绑设备?"
                                  description={`确定要解绑设备 ${item.deviceName} 吗?`}
                                  onConfirm={() => handleUnbindDevice(item.id)}
                                  okText="确认"
                                  cancelText="取消"
                                >
                                  <AButton
                                    type="text"
                                    danger
                                    size="small"
                                    className="unbind-button"
                                  >
                                    解绑
                                  </AButton>
                                </APopconfirm>
                              </div>
                              <div className="device-meta flex justify-between items-center text-sm">
                                <div className="meta-item flex-1 mr-2">
                                  <span className="meta-label text-gray-500 mr-1">产品:</span>
                                  <span
                                    className="meta-value"
                                    title={item.productName || item.productCode || '-'}
                                  >
                                    {item.productName || item.productCode || '--'}
                                  </span>
                                </div>
                                <div className="meta-item flex-1">
                                  <span className="meta-label text-gray-500 mr-1">编码:</span>
                                  <span className="meta-value" title={item.code || '-'}>
                                    {item.code || '-'}
                                  </span>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <div className="empty-devices">
                          <div className="icon-wrapper">
                            <SvgIcon name="icon-bind" />
                          </div>
                          <div className="empty-text">暂无绑定设备</div>
                        </div>
                      )}
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 新增位置模态框 */}
      <ADrawer
        destroyOnHidden
        title={`${OperationTypeList[drawerType].label}空间目录`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType != 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <AForm
          form={form}
          layout="vertical"
          labelAlign="right"
          className="w-full"
          labelCol={{ span: 6 }}
        >
          <ARow className="w-full">
            <ACol span={24}>
              <AForm.Item
                label="上级位置"
                name="parentId"
                rules={[{ required: true, message: '请选择上级位置' }]}
              >
                <ATreeSelect
                  treeDefaultExpandAll
                  treeData={treeDataToAntdTree(treeData, currentRecord?.id || '')}
                  placeholder="请选择上级位置"
                  allowClear
                ></ATreeSelect>
              </AForm.Item>
            </ACol>
            {currentRecord.id && (
              <ACol span={24}>
                <AForm.Item
                  label="位置ID"
                  name="id"
                  rules={[{ required: true, message: '请输入id' }]}
                >
                  <AInput disabled placeholder="请输入id" />
                </AForm.Item>
              </ACol>
            )}
            <ACol span={24}>
              <AForm.Item
                label="名称"
                name="name"
                rules={[{ required: true, message: '请输入名称' }]}
              >
                <AInput placeholder="请输入位置名称" />
              </AForm.Item>
            </ACol>
            <ACol span={24}>
              <AForm.Item
                label="位置编码"
                name="code"
                rules={[{ required: true, message: '请输入位置编码' }]}
              >
                <AInput placeholder="请输入位置编码" />
              </AForm.Item>
            </ACol>
            <ACol span={24} className="relative mb-2">
              <AForm.Item
                label="详细地址"
                name="address"
                rules={[{ required: false, message: '请输入详细地址' }]}
              >
                <AInput placeholder="请输入详细地址" />
              </AForm.Item>
              <span
                onClick={() => setMapOpen(true)}
                className="color-primary cursor-pointer absolute bottom-0 left-0 flex-center"
              >
                <SvgIcon name="icon-location" className=" text-4 mr-0.5" />
                地图选点
              </span>
            </ACol>
            <ACol span={24}>
              <AForm.Item
                label="纬度"
                name="lat"
                rules={[{ required: false, message: '请输入纬度"称' }]}
              >
                <AInput placeholder="请输入位置纬度" />
              </AForm.Item>
            </ACol>
            <ACol span={24}>
              <AForm.Item
                label="经度"
                name="lng"
                rules={[{ required: false, message: '请输入经度' }]}
              >
                <AInput placeholder="请输入位置经度" />
              </AForm.Item>
            </ACol>
            <ACol span={24}>
              <AForm.Item
                label="排序"
                name="sort"
                rules={[{ required: false, message: '请输入排序' }]}
              >
                <AInput placeholder="请输入排序" />
              </AForm.Item>
            </ACol>
            {/* <ACol span={24}>
              <AForm.Item
                label="类型"
                name="type"
                rules={[{ required: false, message: '请选类型' }]}
              >
                <ASelect
                  options={objToArray(DeviceLocationType)}
                  placeholder="请选择位置类型"
                ></ASelect>
              </AForm.Item>
            </ACol> */}
            <ACol span={24} className="relative mb-2">
              <AForm.Item
                label="关联组态图/设备"
                name="configDiagramId"
                rules={[{ required: false, message: '请输入关联组态图/设备' }]}
              >
                <RemoteSelect
                  searchable
                  // 使用独立的状态来控制禁用行为，只有在绑定了设备时禁用
                  disabled={disableConfigSelection}
                  onSelect={(e, options) => {
                    form.setFieldValue('configDiagramName', options?.label);

                    // 设置为有组态图
                    const hasConfig = !!e;
                    setHasConfigDiagram(hasConfig);

                    console.log('选择组态图:', e, '组态图名称:', options?.label);

                    // 选择组态图时清空设备IDs
                    if (hasConfig) {
                      form.setFieldValue('deviceIds', []);
                      setHasBindDevices(false);
                      // 选择组态图时确保不禁用选择器
                      setDisableConfigSelection(false);
                    }
                  }}
                  onChange={value => {
                    console.log('组态图值变化:', value);

                    // 当清空组态图时重置状态
                    if (!value) {
                      setHasConfigDiagram(false);
                      // 清空组态图时，如果有设备绑定则禁用组态图选择器
                      if (hasBindDevices) {
                        setDisableConfigSelection(true);
                      }
                    } else {
                      setHasConfigDiagram(true);
                      form.setFieldValue('deviceIds', []);
                      setHasBindDevices(false);
                      // 选择组态图时确保不禁用选择器
                      setDisableConfigSelection(false);
                    }
                  }}
                  fetchData={fetchRemoteSelectDataGraph}
                />
              </AForm.Item>
              {hasBindDevices && !hasConfigDiagram && (
                <div className="absolute right-0 bottom-0 text-xs text-gray-500">
                  已绑定设备，不能关联组态图
                </div>
              )}
              {hasBindDevices && hasConfigDiagram && (
                <div className="absolute right-0 bottom-0 text-xs text-gray-500">
                  已同时绑定组态图和设备，可修改组态图
                </div>
              )}
              <span
                onClick={() => {
                  if (hasConfigDiagram) {
                    window.$message.warning('当前节点已经绑定组态图，无法直接绑定设备');
                    return;
                  }
                  form.setFieldValue('bindType', 1);
                  setDrawerShowTwo(true);
                }}
                className={`cursor-pointer absolute bottom-0 left-0 flex-center ${hasConfigDiagram ? 'color-gray' : 'color-primary'}`}
              >
                <SvgIcon name="icon-bind" className=" text-4 mr-0.5" />
                跳过组态图直接绑定设备
              </span>
            </ACol>
            <ACol span={24}>
              <AForm.Item label="备注" name="remark">
                <AInput.TextArea placeholder="备注" rows={4} />
              </AForm.Item>
            </ACol>
          </ARow>
        </AForm>
      </ADrawer>
      {/* 绑定设备 */}
      <ADrawer
        destroyOnHidden
        title={`跳过组态图直接绑定设备`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShowTwo(false);
                }}
              >
                返回
              </AButton>
              {drawerType != 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerCloseTwo}
        open={drawerShowTwo}
      >
        <AForm
          form={form}
          initialValues={{
            bindType: 1,
          }}
          layout="vertical"
          labelAlign="right"
          className="w-full"
          labelCol={{ span: 6 }}
        >
          <ARow className="w-full">
            <ACol span={24}>
              <AForm.Item
                label="绑定设备"
                name="bindType"
                rules={[{ required: true, message: '请选择绑定设备' }]}
              >
                <ARadio.Group
                  onChange={() => {
                    form.setFieldValue('deviceIds', []);
                  }}
                  options={[
                    {
                      value: 1,
                      label: '不通过设备分组',
                    },
                    {
                      value: 2,
                      label: '通过设备分组',
                    },
                    {
                      value: 3,
                      label: '通过摄像头分类',
                    },
                  ]}
                ></ARadio.Group>
              </AForm.Item>
            </ACol>

            {/* 原有的设备分组选择 */}
            {bindType == 2 && (
              <ACol span={24}>
                <AForm.Item label="选择设备分组" name="groupId">
                  <RemoteSelect
                    onSelect={() => {
                      form.setFieldValue('deviceIds', []);
                    }}
                    searchable
                    fetchData={fetchRemoteSelectDataDeviceGroup}
                  />
                </AForm.Item>
              </ACol>
            )}

            {/* 新增的摄像头分类选择 */}
            {bindType == 3 && (
              <ACol span={24}>
                <AForm.Item label="摄像头类型" name="cameraCategory">
                  <ASelect
                    options={cameraTypeOptions}
                    placeholder="请选择摄像头类型"
                    allowClear
                    onChange={() => {
                      form.setFieldValue('deviceIds', []);
                    }}
                  />
                </AForm.Item>
              </ACol>
            )}

            <ACol span={24}>
              <>
                {bindType === 3 && (
                  <AForm.Item label="选择摄像头" name="cameraIds">
                    <RemoteSelect
                      searchable
                      searchParams={cameraParams}
                      mode="multiple"
                      onSelect={(e, options) => {
                        console.log('选择设备:', e, options);
                        const selectedDevices = form.getFieldValue('cameraIds') || [];
                        const hasDevices = selectedDevices.length > 0;
                        setHasBindDevices(hasDevices);
                        setDisableConfigSelection(hasDevices);
                        if (hasDevices) {
                          form.setFieldValue('configDiagramId', null);
                          form.setFieldValue('configDiagramName', null);
                          setHasConfigDiagram(false);
                        }
                      }}
                      onChange={value => {
                        console.log('设备变化:', value);
                        const hasDevices = value && value.length > 0;
                        setHasBindDevices(hasDevices);
                        setDisableConfigSelection(hasDevices);
                        if (hasDevices) {
                          form.setFieldValue('configDiagramId', null);
                          form.setFieldValue('configDiagramName', null);
                          setHasConfigDiagram(false);
                        }
                      }}
                      fetchData={fetchRemoteSelectDataCamera}
                    />
                  </AForm.Item>
                )}
                {bindType !== 3 && (
                  <AForm.Item label="已选择设备列表" name="deviceIds">
                    <RemoteSelect
                      searchable
                      searchParams={deviceParams}
                      mode="multiple"
                      onSelect={(e, options) => {
                        console.log('选择设备:', e, options);
                        const selectedDevices = form.getFieldValue('deviceIds') || [];
                        const hasDevices = selectedDevices.length > 0;
                        setHasBindDevices(hasDevices);
                        setDisableConfigSelection(hasDevices);
                        if (hasDevices) {
                          form.setFieldValue('configDiagramId', null);
                          form.setFieldValue('configDiagramName', null);
                          setHasConfigDiagram(false);
                        }
                      }}
                      onChange={value => {
                        console.log('设备变化:', value);
                        const hasDevices = value && value.length > 0;
                        setHasBindDevices(hasDevices);
                        setDisableConfigSelection(hasDevices);
                        if (hasDevices) {
                          form.setFieldValue('configDiagramId', null);
                          form.setFieldValue('configDiagramName', null);
                          setHasConfigDiagram(false);
                        }
                      }}
                      fetchData={fetchRemoteSelectDataDevice}
                    />
                  </AForm.Item>
                )}
              </>
              {hasConfigDiagram && (
                <div className="text-xs text-gray-500 mt-1">注意：添加设备将清除已绑定的组态图</div>
              )}
            </ACol>
          </ARow>
        </AForm>
      </ADrawer>
    </div>
  );
};

export default DeviceLocation;
